package vip.aster.tenant.handler;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import vip.aster.framework.security.entity.SecurityUser;
import vip.aster.tenant.properties.TenantProperties;
import vip.aster.tenant.utils.TenantUtils;

import java.util.List;

/**
 * 自定义租户处理器
 *
 * @author Aster
 * @since 2024/3/22 17:42
 */
@Slf4j
@AllArgsConstructor
public class AsterTenantLineHandler implements TenantLineHandler {

    private final TenantProperties tenantProperties;

    @Override
    public Expression getTenantId() {
        String tenantId = TenantUtils.getTenantId();
        if (StrUtil.isBlank(tenantId)) {
            log.error("无法获取有效的租户id -> Null");
            return new NullValue();
        }
        // 返回固定租户
        return new StringValue(tenantId);
    }

    @Override
    public boolean ignoreTable(String tableName) {
        // 租户id
        String tenantId = TenantUtils.getTenantId();
        // 判断是否有租户
        if (StrUtil.isNotBlank(tenantId)) {
            // 不需要过滤租户的表
            List<String> excludes = tenantProperties.getIgnoreTables();
            // 非业务表
            List<String> tables = ListUtil.toList(
                    "gen_base_class",
                    "gen_datasource",
                    "gen_field_type",
                    "gen_project_modify",
                    "gen_table",
                    "gen_table_field",
                    "qrtz_blob_triggers",
                    "qrtz_calendars",
                    "qrtz_cron_triggers",
                    "qrtz_fired_triggers",
                    "qrtz_job_details",
                    "qrtz_locks",
                    "qrtz_paused_trigger_grps",
                    "qrtz_scheduler_state",
                    "qrtz_simple_triggers",
                    "qrtz_simprop_triggers",
                    "qrtz_triggers",
                    "schedule_job",
                    "schedule_job_log"
            );
            tables.addAll(excludes);
            return tables.contains(tableName);
        }
        return true;

    }
}
